/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.rentalofconstructionmachineryweb.controller;

import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.CustomerDTO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.MachineDTO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.RentalDTO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.service.CustomerService;
import cz.muni.fi.pa165.rentalofconstructionmachinery.service.MachineService;
import cz.muni.fi.pa165.rentalofconstructionmachinery.service.RentalService;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.hibernate.mapping.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author stefan
 */
@Controller
@RequestMapping("/rental")
public class RentalController {

    private RentalService rentalService;
    private MachineService machineService;
    private CustomerService customerService;

    @RequestMapping("")
    public String accountList(Model model) {
        model.addAttribute("rentals", rentalService.getAllRentals());
        return "rental";
    }
    
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    public String getNew(@RequestParam("concreteMachineId") Long concreteMachineId, Model model) {
        MachineDTO machine = null;
        if(null != concreteMachineId && -1 != concreteMachineId) {
            machine = machineService.searchForMachineById(concreteMachineId);
        }
        List<MachineDTO> machines = (null != machine) ? Collections.singletonList(machine) : machineService.listMachines();
        List<CustomerDTO> customers = customerService.getAllCustomers();
        if(0 == machines.size() || 0 == customers.size()) return "redirect:/rental?error&msg=No customer or no machine found";
        model.addAttribute("machines", machines);
        model.addAttribute("customers", customers);
        return "rentalForm";
    }
    
    @RequestMapping(value = "/new", method = RequestMethod.POST)
    public String postNew(@RequestParam("since") String sinceStr, @RequestParam("duration") Integer duration, @RequestParam("customerId") Long customerId, @RequestParam("machineId") Long machineId, Model model) {
        if(null == sinceStr || 0 == sinceStr.length() || null == duration || null == customerId || null == machineId) {
            return "redirect:/rental?error&msg=Some fields not correctly populated";
        } else {
            CustomerDTO customer = customerService.getCustomerById(customerId);
            if(null == customer) return "redirect:/rental?error&msg=Customer with given Id doesn't exist";
            MachineDTO machine = machineService.searchForMachineById(machineId);
            if(null == machine) return "redirect:/rental?error&msg=Machine with given Id doesn't exist";
        
            Date since;
            try {
                since = new SimpleDateFormat("yyyy-MM-dd").parse(sinceStr);
            } catch (Exception ex) {
                return "redirect:/rental?error&msg=Bad date format";
            }

            RentalDTO newRental = new RentalDTO();
            newRental.setCustomer(customer);
            newRental.setMachine(machine);
            newRental.setSince(since);
            newRental.setDuration(duration);
            rentalService.addRental(newRental);

            return "redirect:/rental?success";
        }
    }
    
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public String getEdit(@PathVariable Long id, Model model) {
        if(null == id) {
            return "redirect:/rental?error&msg=Rental Id not provided";
        } else {
            RentalDTO rental = rentalService.getRentalById(id);
            if(null == rental) return "redirect:/rental?error&msg=Rental with given Id doesn't exist";
            model.addAttribute("machines", machineService.listMachines());
            model.addAttribute("customers", customerService.getAllCustomers());
            model.addAttribute("rental", rental);
            return "rentalForm";
        }
    }
    
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.POST)
    public String postEdit(@PathVariable Long id, @RequestParam("since") String sinceStr, @RequestParam("duration") int duration, @RequestParam("customerId") Long customerId, @RequestParam("machineId") Long machineId, Model model) {
        if(null == sinceStr || 0 == sinceStr.length() || null == customerId || null == machineId || null == id) {
            return "redirect:/rental?error&msg=Some fields not correctly populated";
        } else {
            RentalDTO rental = rentalService.getRentalById(id);
            if(null == rental) return "redirect:/rental?error&msg=Rental with given Id doesn't exist";
            CustomerDTO customer = customerService.getCustomerById(customerId);
            if(null == customer) return "redirect:/rental?error&msg=Customer with given Id doesn't exist";
            MachineDTO machine = machineService.searchForMachineById(machineId);
            if(null == machine) return "redirect:/rental?error&msg=Machine with given Id doesn't exist";

            Date since;
            try {
                since = new SimpleDateFormat("yyyy-MM-dd").parse(sinceStr);
            } catch (Exception ex) {
                return "redirect:/rental?error&msg=Bad date format";
            }

            rental.setCustomer(customer);
            rental.setMachine(machine);
            rental.setSince(since);
            rental.setDuration(duration);
            rentalService.modifyRental(rental);

            return "redirect:/rental?success";
        }
    }
    
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public String delete(@PathVariable Long id, Model model) {
        if(null == id) return "redirect:/rental?error&msg=Rental Id not provided";
        RentalDTO rental = rentalService.getRentalById(id);
        if(null == rental) return "redirect:/rental?error&msg=Rental with given Id doesn't exist";
        rentalService.removeRental(rental);
        return "redirect:/rental?success";
    }

    @Autowired
    public RentalController(RentalService rentalService, CustomerService customerService, MachineService machineService) {
        this.rentalService = rentalService;
        this.customerService = customerService;
        this.machineService = machineService;
    }
}
